package com.ww.springboot.boot.thread.study.eg;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.IntStream;

/**
 * 描述：ArrayList线程不安全案例1 --
 *
 * 分析：多线程下读写共用同一份数据 且未加锁 竞争导致不安全
 * 
 * CopyOnWrite :写加锁  多写入时效率不高  多读取时性能很强 读写分别使用一份副本
 *
 * @author wanwei
 * @since 2021-05-20 16:47
 */
public class ArrayListUnSafe1 {

    public static void main(String[] args) {
        List<Integer> numList = new ArrayList<>();
        List<Integer> numList2 = new CopyOnWriteArrayList<>();
        IntStream.range(0,10000).boxed().parallel().forEach(i->{
            numList.add(i);
            numList2.add(i);
            // 此句会报错
            System.out.println(numList.toString());
            //System.out.println(numList2.size());
        });
        System.out.println(numList);
        System.out.println(numList.contains(null));
        System.out.println(numList.size());
        System.out.println(numList2);
        System.out.println(numList2.contains(null));
        System.out.println(numList2.size());
    }
}
